﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using TimedText.Timing;
using System.Xml;
using System.IO;

namespace TimedText.Utilities
{
    public sealed class TimedTextParser
    {
        private TimedTextParser() { }

        public static TtElement Parse(string text)
        { 
            TtElement parsetree = null;

            try
            {
                XDocument xml = XDocument.Parse(text);
                parsetree = (TtElement)TimedTextElementBase.Parse(xml.Root);
            }
            catch (TimedTextException)
            {
               // throw new Exception(e.Message);
            }
            if (parsetree == null)
            {
                throw new TimedTextException("No Parse tree returned");
            }
            if (!parsetree.Valid())
            {
                throw new TimedTextException("Document is Well formed XML, but invalid Timed Text");
            }

            /// to do - we need an external duration (e.g. media length to set the upper bound time).
            TimeCode startTime = new TimeCode("00:00:00:00", Timing.TimeExpression.CurrentSmpteFrameRate);
            TimeCode endTime = new TimeCode("12:00:00:00", Timing.TimeExpression.CurrentSmpteFrameRate);

            parsetree.ComputeTimeIntervals(Timing.TimeContainer.Par, startTime, endTime);

            return parsetree;
        }

        public static string Serialize(TtElement parsetree)
        {
            StringWriter stringWriter = new StringWriter();


            //Creating XmlWriter Settings
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = "  ";
            settings.NewLineOnAttributes = true;

            XmlWriter writer = XmlTextWriter.Create(stringWriter, settings);

            // Start document
            writer.WriteStartDocument();
            writer.WriteComment("Test Serialisation of parse tree");
            parsetree.WriteElement(writer);
            writer.Flush();

            writer.Flush();
            writer.Close();
            stringWriter.Flush();

            return stringWriter.ToString();

        }
    }
}
